<?php

/**
 * @author Martin Pernica
 * @copyright 2008
 */
require ( APPROOT . '/libs/Framework/System.php');
$_system = new System();

foreach (glob( APPROOT . "/libs/Framework/*.php") as $lib) {
    if ($lib !=  APPROOT . '/libs/Framework/System.php') {
        require_once ($lib);
    }
}

foreach (glob( APPROOT . "/libs/Framework/HTML/*.php") as $lib) {
    require_once ($lib);
}

foreach (glob( APPROOT . "/libs/*.php") as $lib) {
    require_once ($lib);
}

ErrorHandler::Initialize();

Registry::set("db", $GLOBALS['db']);
Registry::set("db_prefix", $GLOBALS['db_prefix']);

class Page
{
    var $page;
    var $q;
    var $header;
    var $title;

    public $count_file = 0;
    public $count_text = 0;
    public $count_header = 0;

    public $db;
    public $log;
    public $visitors_online;

    function Page($template = "default", $language = "czech", $q)
    {

        $this->q = $q;
        $this->db = $GLOBALS['db'];
        $this->log = new Log('database');
        $this->visitors_online = new usersOnline();
        $tlp_path = './templates/' . $template . '/';
        $GLOBALS['page'] = &$this;
        Registry::set("page", $this);

        if (empty($_GET['q'])) {
            $q = explode("/", $GLOBALS['setting']['default_view']);
            $this->q = $q;
            $view = $q[0];
        } else {
            $view = htmlspecialchars(addslashes($q[0]));
        }

        if (file_exists($tlp_path . 'index.php')) {
            $this->page = self::parse($tlp_path . '/index.php');
        } else {
            $this->log->write(1, 'template', 'NOW()', "Fatal Error : Template file " . $tlp_path .
                " not found.", 0);
            exit("Fatal Error : Template file " . $tlp_path . " not found.");
        }

        $modules = dirlist("./modules");
        $modules_tags = array();
        foreach ($modules as $key) {
            $modules_tags["file_" . $key] = $key . DIR_SEP . $key . ".php";
        }

        $replace_tags = array("text_staticTitle" => $GLOBALS['setting']['web_title'],
            "text_headline" => $GLOBALS['setting']['web_title'], "text_subTitle" => $GLOBALS['setting']['web_subTitle'],
            "text_charset" => $GLOBALS['setting']['web_charset'], "text_description" => $GLOBALS['setting']['web_description'],
            "text_keywords" => $GLOBALS['setting']['web_keywords'], "text_author" => $GLOBALS['setting']['web_author'],
            "text_lang" => $language, "text_tlpdir" => $GLOBALS['url'] . 'templates/' . $template .
            '/', "file_com_main" => "com_" . $view . DIR_SEP . "com_" . $view . ".php",
            "text_header" => '', "text_title" => $GLOBALS['setting']['web_title'],
            "text_url" => $GLOBALS['url']);
        $tags = array_merge($modules_tags, $replace_tags);
        self::replace_tags($tags);
    }

    function header($type = 'script', $second = '')
    {
        if ($type == 'script') {
            $this->header .= "\n" . "<script type=\"text/javascript\" src=\"" . $second . "\"></script>";
        } else
            if ($type == 'style') {
                $this->header .= "\n" . "<link href=\"" . $second . "\" rel=\"stylesheet\" type=\"text/css\" />";
            } else
                if ($type == 'text') {
                    $this->header .= "\n" . $second;
                }
    }

    function setTitle($text)
    {
        $this->title = $text;
        return true;
    }

    function getPermission($com)
    {
        $query = $GLOBALS['db']->query("SELECT frontend FROM {prefix}permissions WHERE component = 'com_" .
            $com . "'");
        $query = $query->fetch_array();
        return intval($query[0]);
    }

    function parse($file)
    {
        ob_start();
        $q = &$this->q;
        Registry::set("q", $this->q);
        $db = &$GLOBALS['db'];
        $log = &$this->log;
        Registry::set("log", $this->log);
        $visitors_online = &$this->visitors_online;
        Registry::set("visitors_online", $this->visitors_online);
        include ($file);
        $buffer = ob_get_contents();
        ob_end_clean();
        return $buffer;
    }

    function replace_tags($tags = array())
    {
        if (sizeof($tags) > 0) {
            foreach ($tags as $tag => $data) {

                $tag = explode("_", $tag);
                if ($tag[0] == 'file') {
                    if (preg_match("/{" . $tag[2] . "}/i", $this->page)) {
                        $path = ($tag[1] == 'mod') ? './modules/' : './components/';
                        $_SESSION['location'] = ($tag[2] == 'main') ? $_GET['q'] : '';
                        $this->count_file++;
                        $data = $path . htmlspecialchars(addslashes($data));
                        if (file_exists($data)) {
                            $data = $this->parse($data);
                        } else {

                            $this->log->write(2, 'System', 'NOW()', 'User opened the non-existent file (' .
                                $data . ') !', intval($_SESSION['id']));
                            $data = '<h2>File not found !</h2><p>The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.</p>';
                        }
                        $this->page = preg_replace("/{" . $tag[2] . "}/i", $data, $this->page);
                    }
                } else
                    if ($tag[0] == 'text') {
                        $this->count_text++;
                        if ($tag[1] == 'title') {
                            $title = (empty($this->title)) ? '' : ' - ' . $this->title;
                            $data = $data . $title;
                            $this->page = preg_replace("/{" . $tag[1] . "}/i", $data, $this->page, 1);
                        } else
                            if ($tag[1] == 'header') {
                                $this->count_header++;
                                $data = $this->header;
                                $this->page = preg_replace("/{" . $tag[1] . "}/i", $data, $this->page, 1);
                            } else {
                                $this->page = preg_replace("/{" . $tag[1] . "}/i", $data, $this->page);
                            }

                    }
            }
        } else {
            exit('No tags designated for replacement.');
        }
    }

    function output()
    {
        $a = ($GLOBALS['seo']) ? str_replace('index.php?q=', '', $this->page) : $this->
            page;

        if (System::$Debug) {
            $tmp = (string )"";
            foreach (Registry::get("db")->queries_log as $key => $val) {
                $tmp .= $val . "\n<br />\n";
            }

            $a = str_replace('{queries_log}', $tmp, $a);
            $a = str_replace('{queries}', Registry::get("db")->query_count, $a);
        }

        echo $a;
    }
}

?>